﻿using System;
using System.Windows.Input;
using System.Windows;
using WickedFlame.Core.Shapes;

namespace WickedFlame.Core.Tools
{
    public class TextTool : FactoryTool
    {
        TextShape textShape;

        public TextTool()
            : base()
        {
        }

        protected override VectorShape CreateShape(Point mousePosition)
        {
			if (textShape != null)
			{
				textShape.IsInEditMode = false;
				textShape.IsSelected = false;
			}

            textShape = new TextShape(mousePosition);
            textShape.FontSize = ShapePropertySettings.Settings.FontSize;
            textShape.FontFamily = ShapePropertySettings.Settings.FontFamily;
            textShape.Stroke = ShapePropertySettings.Settings.Stroke;

            textShape.IsSelected = true;

            return textShape;
        }

        public override void OnMouseLeftButtonUp(DrawingCanvas sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            //Add object to history
            if (textShape == null)
                return;

            sender.PushHistoryCommand(new WickedFlame.Core.History.AddCommand(textShape, sender.SelectedLayerIndex));
            textShape.CallChangeEndHandler();
        }

        public override void OnKeyDown(DrawingCanvas sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
                if (textShape != null)
                {
                    sender.RemoveShape(textShape);
                    sender.HistoryManager.RemoveLastCommand();
                    textShape = null;
                }
        }

        public override void OnTextInput(DrawingCanvas sender, TextCompositionEventArgs e)
        {
            if (textShape != null)
            {
                if (e.Text == "\b")
                {
                    if (textShape.Text.Length > 0)
                        textShape.Text = textShape.Text.Substring(0, textShape.Text.Length - 1);
                }
                else
                {
                    textShape.Text += e.Text;
                }
                textShape.Invalidate();
            }
        }

        public override void OnDeactivate(DrawingCanvas sender)
        {
            if (textShape != null)
            {
                if (string.IsNullOrEmpty(textShape.Text))
                {
                    sender.RemoveShape(textShape);
                    sender.HistoryManager.RemoveLastCommand();
                    textShape = null;
                }
                else
                    textShape.IsInEditMode = false;

                if (textShape != null)
                    textShape.CallChangeEndHandler();
            }
        }
    }
}
